package com.ruoyi.business.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.business.app.bo.AppDirectBo;
import com.ruoyi.business.app.bo.AppSecondBo;
import com.ruoyi.business.app.service.IMyTeamService;
import com.ruoyi.business.app.vo.*;
import com.ruoyi.business.domain.HcxAppUser;
import com.ruoyi.business.domain.HcxMerchantOrder;
import com.ruoyi.business.domain.HcxWithdrawDetail;
import com.ruoyi.business.enums.VipFlagEnum;
import com.ruoyi.business.mapper.HcxAppUserMapper;
import com.ruoyi.business.mapper.HcxMerchantOrderMapper;
import com.ruoyi.business.mapper.HcxWithdrawDetailMapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.page.PagePlus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class MyTeamServiceImpl  extends ServicePlusImpl<HcxAppUserMapper, HcxAppUser>  implements IMyTeamService {

    private final HcxWithdrawDetailMapper hcxWithdrawDetailMapper;

    private final HcxMerchantOrderMapper hcxMerchantOrderMapper;

    @Override
    public AppMyProfitVo profit() {

        // 当前登录用户
        HcxAppUser currentAppUser = getBaseMapper().selectById(SecurityUtils.getUserId());

        // 累计收益账单=余额收益账单+农产品收益账单+推广奖账单
        List<HcxWithdrawDetail> totalList = hcxWithdrawDetailMapper.selectList(new LambdaQueryWrapper<HcxWithdrawDetail>()
                .eq(HcxWithdrawDetail::getUserId, SecurityUtils.getUserId())
                .in(HcxWithdrawDetail::getDetailType, Arrays.asList("2", "3", "4")));
        BigDecimal totalPrice = totalList.stream().map(HcxWithdrawDetail::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2,BigDecimal.ROUND_HALF_UP);

        // 本周收益账单=余额收益账单+农产品收益账单+推广奖账单
        List<HcxWithdrawDetail> weekList = hcxWithdrawDetailMapper.selectList(new LambdaQueryWrapper<HcxWithdrawDetail>()
                .eq(HcxWithdrawDetail::getUserId, SecurityUtils.getUserId())
                .in(HcxWithdrawDetail::getDetailType, Arrays.asList("2", "3", "4"))
                .between(HcxWithdrawDetail::getCreateTime,DateUtil.beginOfWeek(new Date()),DateUtil.endOfWeek(new Date())));
        BigDecimal weekPrice = weekList.stream().map(HcxWithdrawDetail::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2,BigDecimal.ROUND_HALF_UP);

        // 直接推荐的人数
        Integer directNum = getBaseMapper().selectCount(new LambdaQueryWrapper<HcxAppUser>().
                eq(HcxAppUser::getInviteFullCode, currentAppUser.getInviteFullCode() + currentAppUser.getInviteCode())
                .eq(HcxAppUser::getVipFlag, VipFlagEnum.ISVIP.getValue())
        );


        String  fulleCode=currentAppUser.getInviteFullCode() + currentAppUser.getInviteCode();
        // 间接推荐的人数
        int indirectNum = getBaseMapper().jianjieTuiguang(fulleCode);


        AppMyProfitVo appMyProfitVo=new AppMyProfitVo();
        appMyProfitVo.setTotalPrice(totalPrice);
        appMyProfitVo.setWeekPrice(weekPrice);
        appMyProfitVo.setDirectNum(directNum);
        appMyProfitVo.setIndirectNum(indirectNum);

        return appMyProfitVo;
    }

    @Override
    public TableDataInfo<AppDirectVo> queryAppPageList(AppDirectBo bo) {
        // 查询当前登录用户
        HcxAppUser hcxAppUser = getBaseMapper().selectById(SecurityUtils.getUserId());
        LambdaQueryWrapper<HcxAppUser> lqw = Wrappers.lambdaQuery();
        lqw.eq(HcxAppUser::getInviteFullCode, hcxAppUser.getInviteFullCode()+hcxAppUser.getInviteCode())
        .eq(HcxAppUser::getVipFlag,Constants.ONE).orderByAsc(HcxAppUser::getVipTime);
        PagePlus<HcxAppUser, AppDirectVo> result = pageVo(PageUtils.buildPagePlus(), lqw, AppDirectVo.class);
        List<AppDirectVo> recordsVo = result.getRecordsVo();
        for (AppDirectVo appDirectVo : recordsVo) {
            // 查询用户的累计消费 = 购买商家商品消费+购买洗车卡消费 (即查询用户的所有已支付订单)
            List<HcxMerchantOrder> hcxMerchantOrders = hcxMerchantOrderMapper.selectList(new LambdaQueryWrapper<HcxMerchantOrder>()
                    .eq(HcxMerchantOrder::getStatus, Constants.ONE)
                    .eq(HcxMerchantOrder::getUserId,appDirectVo.getId())
            );
            BigDecimal totalPrice = hcxMerchantOrders.stream().map(HcxMerchantOrder::getActualPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
            appDirectVo.setTotalPrice(totalPrice);
        }
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public AppDirectDetailVo directDetail(Long userId) {

        HcxAppUser hcxAppUser = getBaseMapper().selectById(userId);

        // 累计收益账单=余额收益账单+农产品收益账单+推广奖账单
        List<HcxWithdrawDetail> totalList = hcxWithdrawDetailMapper.selectList(new LambdaQueryWrapper<HcxWithdrawDetail>()
                .eq(HcxWithdrawDetail::getUserId, userId)
                .in(HcxWithdrawDetail::getDetailType, Arrays.asList("2", "3", "4")));
        BigDecimal totalPrice = totalList.stream().map(HcxWithdrawDetail::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2,BigDecimal.ROUND_HALF_UP);

        // 本周收益账单=余额收益账单+农产品收益账单+推广奖账单
        List<HcxWithdrawDetail> weekList = hcxWithdrawDetailMapper.selectList(new LambdaQueryWrapper<HcxWithdrawDetail>()
                .eq(HcxWithdrawDetail::getUserId, userId)
                .in(HcxWithdrawDetail::getDetailType, Arrays.asList("2", "3", "4"))
                .between(HcxWithdrawDetail::getCreateTime,DateUtil.beginOfWeek(new Date()),DateUtil.endOfWeek(new Date())));
        BigDecimal weekPrice = weekList.stream().map(HcxWithdrawDetail::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2,BigDecimal.ROUND_HALF_UP);


        AppDirectDetailVo appDirectDetailVo = new AppDirectDetailVo();
        appDirectDetailVo.setNickName(hcxAppUser.getNickName());
        appDirectDetailVo.setPhonenumber(hcxAppUser.getPhonenumber().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
        appDirectDetailVo.setCreateTime(hcxAppUser.getCreateTime());
        appDirectDetailVo.setWeekPrice(weekPrice);
        appDirectDetailVo.setTotalPrice(totalPrice);
        return appDirectDetailVo;
    }

    @Override
    public TableDataInfo<AppSecondVo> queryAppSecondPageList(AppSecondBo bo) {
        // 查询当前登录用户
        HcxAppUser hcxAppUser = getBaseMapper().selectById(bo.getId());
        LambdaQueryWrapper<HcxAppUser> lqw = Wrappers.lambdaQuery();
        lqw.eq(HcxAppUser::getInviteFullCode, hcxAppUser.getInviteFullCode()+hcxAppUser.getInviteCode()).eq(HcxAppUser::getVipFlag,Constants.ONE).orderByAsc(HcxAppUser::getVipTime);
        PagePlus<HcxAppUser, AppSecondVo> result = pageVo(PageUtils.buildPagePlus(), lqw, AppSecondVo.class);
        List<AppSecondVo> recordsVo = result.getRecordsVo();
        for (AppSecondVo appSecondVo : recordsVo) {
            // 查询用户的累计消费 = 购买商家商品消费+购买洗车卡消费 (即查询用户的所有已支付订单)
            List<HcxMerchantOrder> hcxMerchantOrders = hcxMerchantOrderMapper.selectList(new LambdaQueryWrapper<HcxMerchantOrder>()
                    .eq(HcxMerchantOrder::getStatus, Constants.ONE)
                    .eq(HcxMerchantOrder::getUserId,appSecondVo.getId()));
            BigDecimal totalPrice = hcxMerchantOrders.stream().map(HcxMerchantOrder::getActualPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
            appSecondVo.setTotalPrice(totalPrice);
        }
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public TableDataInfo<AppWithdrawDetailVo> queryZhangdanPageList(Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<HcxWithdrawDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(HcxWithdrawDetail::getUserId,SecurityUtils.getUserId());
        lqw.in(HcxWithdrawDetail::getDetailType,Arrays.asList("2","3","4"));

        PagePlus<HcxWithdrawDetail, AppWithdrawDetailVo> result = hcxWithdrawDetailMapper.selectPage(PageUtils.buildPagePlus(), lqw);
        List<AppWithdrawDetailVo> volist = result.getRecords().stream()
                .map(any -> BeanUtil.toBean(any, AppWithdrawDetailVo.class))
                .collect(Collectors.toList());
        result.setRecordsVo(volist);
        return PageUtils.buildDataInfo(result);
    }

    public static void main(String[] args) {



    }
}
